package com.xm.limiter;

/**
 * 令牌桶算法
 */
public class TokenBucketLimiter03 implements Limiter {
    private final int capacity; // 桶容量
    private final double rate; // 令牌生成速率（个/毫秒）
    private int tokens; // 当前令牌数
    private long lastTime = System.currentTimeMillis();

    /**
     * 令牌桶算法：需要应对突发流量的系统（如秒杀活动）
     * @param capacity 桶容量
     * @param rate 令牌生成速率（个/毫秒）
     */
    public TokenBucketLimiter03(int capacity, double rate) {
        this.capacity = capacity;
        this.rate = rate;
        this.tokens = capacity;
    }

    @Override
    public synchronized boolean tryAcquire() {
        long now = System.currentTimeMillis();
        long elapsed = now - lastTime;
        tokens = (int) Math.min(capacity, tokens + elapsed * rate);
        lastTime = now;
        if (tokens > 0) {
            tokens--;
            return true;
        }
        return false;
    }
}